import { useClientStore } from '@/stores/client'
import { FetchInsecure, GetImage } from '@wails/client/clientfunc'

// 提取公共的获取token和port以及生成Authorization header的逻辑
function getAuthInfo() {
  const {
    '--remoting-auth-token': token,
    '--app-port': port,
    '--riotclient-app-port': riotPort,
    '--riotclient-auth-token': riotToken,
  } = useClientStore().clientInfo
  if (!token || !port) {
    throw new Error('token 或 port 不存在')
  }
  return { token, port, riotPort, riotToken }
}

export function req<T>(url: string, params?: any, methods: string = 'GET', body?: any): Promise<T> {
  return new Promise(async (resolve, reject) => {
    try {
      const { port, token } = getAuthInfo()
      const Authorization = btoa(`riot:${token}`)

      // 默认参数
      const defaultParams = {
        url: `https://127.0.0.1:${port}${url}`,
        method: methods || 'GET',
        headers: {
          Authorization: `Basic ${Authorization}`,
        },
      }

      // 合并参数
      const finalParams = { ...defaultParams, params, body }
      console.log('执行请求：', finalParams)

      // 发送请求
      const { code, data, msg } = await FetchInsecure(finalParams)

      switch (code) {
        case 200:
          try {
            const res = JSON.parse(data)
            resolve(res)
          } catch (error) {
            resolve(data as T)
          }
          break
        case 401:
          reject(new Error('未授权，请检查token'))
          break
        case 404:
          reject(new Error(`请求的资源不存在: ${url}`))
          break
        case 500:
          reject(new Error(`服务器内部错误：${msg}`))
          break
        default:
          reject(new Error(`未知错误：${msg}`))
          break
      }
    } catch (error) {
      reject(error)
    }
  })
}

export function reqRoit(url: string, params?: any, methods: string = 'GET', body?: any) {
  return new Promise(async (resolve, reject) => {
    try {
      const { riotPort, riotToken } = getAuthInfo()
      const Authorization = btoa(`riot:${riotToken}`)

      // 默认参数
      const defaultParams = {
        url: `https://127.0.0.1:${riotPort}${url}`,
        method: methods || 'GET',
        headers: {
          Authorization: `Basic ${Authorization}`,
        },
      }

      // 合并参数
      const finalParams = { ...defaultParams, params, body }
      console.log('ROIT执行请求：', finalParams)

      // 发送请求
      const { code, data, msg } = await FetchInsecure(finalParams)

      switch (code) {
        case 200:
          try {
            const res = JSON.parse(data)
            resolve(res)
          } catch (error) {
            resolve(data)
          }
          break
        case 401:
          reject(new Error('未授权，请检查riot token'))
          break
        case 404:
          reject(new Error('请求的ROIT资源不存在'))
          break
        case 500:
          reject(new Error(`ROIT服务器内部错误：${msg}`))
          break
        default:
          reject(new Error(`ROIT未知错误：${msg}`))
          break
      }
    } catch (error) {
      reject(error)
    }
  })
}

// 获取图片
export function reqImage(url: string) {
  return new Promise(async (resolve, reject) => {
    try {
      const { port, token } = getAuthInfo()
      const Authorization = btoa(`riot:${token}`)

      // 默认参数
      const defaultParams = {
        url: `https://127.0.0.1:${port}${url}`,
        headers: {
          Authorization: `Basic ${Authorization}`,
        },
      }

      // 发送请求
      const { code, data, msg } = await GetImage(defaultParams)

      switch (code) {
        case 200:
          resolve(`data:image/png;base64,${data}`)
          break
        case 401:
          reject(new Error('未授权，请检查token'))
          break
        case 404:
          resolve(null)
          break
        case 500:
          reject(new Error(`服务器内部错误：${msg}`))
          break
        default:
          reject(new Error(`未知错误：${msg}`))
          break
      }
    } catch (error) {
      reject(error)
    }
  })
}
